package com.leonwoodstudio.eventdetectionclient;

import android.os.Handler;

import com.leonwoodstudio.eventdetectionclient.eventmessage.DownloadPicMessage;
import com.leonwoodstudio.eventdetectionclient.eventmessage.ParsedEventMessageToSave;
import com.leonwoodstudio.eventdetectionclient.utils.FileAccessor;
import com.leonwoodstudio.eventdetectionclient.utils.FtpUtil;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

/**
 * Created by win7 on 2017/4/4.
 */
public class ReceiveEventThread extends Thread {
    Handler handler;
    boolean stop;
    Socket socket;
    public ReceiveEventThread(Handler handler) {
        this.handler = handler;
        stop = false;
        socket = null;
    }

    public void Stop() {
        stop = true;
        try {
            if (socket != null) {
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        super.run();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        handler.obtainMessage(MainActivity.MSG_ACCESS_FILE, null).sendToTarget();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        while(!stop) {
            BufferedInputStream bis = null;
            try {
                socket = new Socket();
                SocketAddress socketAddress = new InetSocketAddress(MainActivity.prop_remote_ip_address, Integer.valueOf(MainActivity.prop_remote_port));
                socket.connect(socketAddress, 3000);
                handler.obtainMessage(MainActivity.MSG_CONNECTION_ESTABLISHED, null).sendToTarget();
                InputStream is = socket.getInputStream();
                bis = new BufferedInputStream(is);
                while(!stop) {
                    byte[] event_message = new byte[100];
                    int len = bis.read(event_message, 0, event_message.length);
                    if (len == -1) {
                        throw new ConnectException("EOF");
                    }
                    String event_message_str = new String(event_message, 0, len, "GBK");
                    System.out.println(event_message_str);
                    String[] tokens = event_message_str.split(" ");
                    if ("A".equals(tokens[0])) {
                        if ("2".equals(tokens[1])) {
                            DownloadPicMessage message = new DownloadPicMessage();
                            message.setType(tokens[1]);
                            message.setCamera(tokens[2]);
                            message.setPicUrlDir(tokens[3]);
                            message.setPicName(tokens[4].replace("dat", "jpg"));

                            ParsedEventMessageToSave parsed = new ParsedEventMessageToSave();
                            parsed.setUrl(message.getPicUrlDir());
                            String pic_name = message.getPicName();
                            parsed.setPic_name(pic_name);
                            parsed.setDate(pic_name.substring(0, 14));
                            parsed.setCamera_idx(pic_name.substring(14, 17));
                            parsed.setLane_inx(pic_name.substring(17,18));
                            parsed.setEvent_type(pic_name.substring(18, 20));
                            parsed.setCoordinate_x(pic_name.substring(20, 23));
                            parsed.setCoordinate_y(pic_name.substring(23, 26));
                            handler.obtainMessage(MainActivity.MSG_RECV_PIC_URL, parsed).sendToTarget();
                        }
                    } else if ("S".equals(tokens[0])) {
                        OutputStream os = socket.getOutputStream();
                        BufferedOutputStream bos = new BufferedOutputStream(os);
                        byte[] sync = new byte[]{0x42, 0x20, 0x16, 0x20, 0x0A};
                        bos.write(sync, 0, sync.length);
                        bos.flush();
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (bis != null) {
                        bis.close();
                    }
                    if (socket != null) {
                        socket.close();
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (!stop) {
                handler.obtainMessage(MainActivity.MSG_CONNECTION_LOST, null).sendToTarget();
            }
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
